<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue';

import { IconifyIcon } from '@vben/icons';

import {
  Button,
  Col,
  Descriptions,
  DescriptionsItem,
  Input,
  message,
  Modal,
  Row,
  Select,
  SelectOption,
  Space,
  Table,
  Tag,
} from 'ant-design-vue';

import CapabilityExecutionModal from './CapabilityExecutionModal.vue';

// 响应式数据
const loading = ref(false);
const executionList = ref([]);
const currentExecution = ref(null);
const detailModalVisible = ref(false);
const executeModalVisible = ref(false);

// 搜索表单
const searchForm = reactive({
  capabilityInstanceId: '',
  status: '',
});

// 分页
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`,
});

// 表格列定义
const columns = [
  {
    title: '执行ID',
    dataIndex: 'id',
    key: 'id',
    width: 120,
  },
  {
    title: '能力实例ID',
    dataIndex: 'capabilityInstanceId',
    key: 'capabilityInstanceId',
    width: 150,
  },
  {
    title: '资源ID',
    dataIndex: 'resourceId',
    key: 'resourceId',
    width: 100,
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100,
  },
  {
    title: '开始时间',
    dataIndex: 'startTime',
    key: 'startTime',
    width: 150,
    customRender: ({ text }: { text: number }) => formatTime(text),
  },
  {
    title: '执行时长',
    key: 'duration',
    width: 100,
  },
  {
    title: '操作',
    key: 'actions',
    width: 200,
    fixed: 'right',
  },
];

// 获取状态颜色
const getStatusColor = (status: string) => {
  const colorMap = {
    pending: 'orange',
    running: 'blue',
    completed: 'green',
    failed: 'red',
    cancelled: 'gray',
  };
  return colorMap[status] || 'default';
};

// 获取状态文本
const getStatusText = (status: string) => {
  const textMap = {
    pending: '等待中',
    running: '执行中',
    completed: '已完成',
    failed: '失败',
    cancelled: '已取消',
  };
  return textMap[status] || status;
};

// 格式化时间
const formatTime = (timestamp: number) => {
  return new Date(timestamp).toLocaleString();
};

// 格式化时长
const formatDuration = (duration: number) => {
  if (duration < 1000) {
    return `${duration}ms`;
  } else if (duration < 60_000) {
    return `${(duration / 1000).toFixed(1)}s`;
  } else {
    return `${(duration / 60_000).toFixed(1)}m`;
  }
};

// 加载数据
const loadData = async () => {
  loading.value = true;
  try {
    // 模拟数据
    const mockExecutions = [
      {
        id: 'exec_1',
        capabilityInstanceId: 'instance_1',
        resourceId: '1',
        status: 'completed',
        parameters: {
          resourceId: '1',
          startTime: '2024-01-01 10:00:00',
          endTime: '2024-01-01 12:00:00',
          userId: 'user_1',
        },
        result: {
          bookingId: 'booking_001',
          status: 'confirmed',
        },
        error: null,
        startTime: Date.now() - 3_600_000,
        endTime: Date.now() - 3_500_000,
        duration: 100_000,
        context: {
          userId: 'user_1',
          sessionId: 'session_1',
          requestId: 'req_1',
        },
      },
      {
        id: 'exec_2',
        capabilityInstanceId: 'instance_2',
        resourceId: '2',
        status: 'running',
        parameters: {
          orderId: 'order_001',
          amount: 1000,
          paymentMethod: 'alipay',
        },
        result: null,
        error: null,
        startTime: Date.now() - 300_000,
        endTime: null,
        duration: null,
        context: {
          userId: 'user_2',
          sessionId: 'session_2',
          requestId: 'req_2',
        },
      },
      {
        id: 'exec_3',
        capabilityInstanceId: 'instance_3',
        resourceId: '3',
        status: 'failed',
        parameters: {
          userId: 'user_3',
          message: '测试消息',
          type: 'sms',
        },
        result: null,
        error: {
          code: 'SEND_FAILED',
          message: '短信发送失败',
          details: {
            reason: '手机号格式错误',
          },
        },
        startTime: Date.now() - 1_800_000,
        endTime: Date.now() - 1_790_000,
        duration: 10_000,
        context: {
          userId: 'user_3',
          sessionId: 'session_3',
          requestId: 'req_3',
        },
      },
    ];

    executionList.value = mockExecutions;
    pagination.total = mockExecutions.length;
  } catch (error) {
    console.error('加载执行记录失败:', error);
    message.error('加载数据失败');
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  pagination.current = 1;
  loadData();
};

// 表格变化
const handleTableChange = (pag: any) => {
  pagination.current = pag.current;
  pagination.pageSize = pag.pageSize;
  loadData();
};

// 刷新数据
const refreshData = () => {
  loadData();
};

// 查看详情
const viewDetail = (record: any) => {
  currentExecution.value = record;
  detailModalVisible.value = true;
};

// 取消执行
const cancelExecution = (record: any) => {
  Modal.confirm({
    title: '确认取消',
    content: `确定要取消执行 "${record.id}" 吗？`,
    onOk: async () => {
      try {
        // TODO: 实现取消执行API调用
        record.status = 'cancelled';
        message.success('取消成功');
      } catch {
        message.error('取消失败');
      }
    },
  });
};

// 下载结果
const downloadResult = (record: any) => {
  if (record.result) {
    const blob = new Blob([JSON.stringify(record.result, null, 2)], {
      type: 'application/json',
    });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `execution_result_${record.id}.json`;
    a.click();
    URL.revokeObjectURL(url);
    message.success('下载成功');
  }
};

// 打开执行模态框
const openExecuteModal = () => {
  executeModalVisible.value = true;
};

// 执行成功回调
const onExecuteSuccess = () => {
  executeModalVisible.value = false;
  loadData();
  message.success('执行成功');
};

// 初始化
onMounted(() => {
  loadData();
});
</script>

<template>
  <div class="capability-execution-manager">
    <div class="manager-header">
      <h2>能力执行管理</h2>
      <div class="header-actions">
        <Button type="primary" @click="openExecuteModal">
          <IconifyIcon icon="ant-design:play-outlined" />
          执行能力
        </Button>
        <Button @click="refreshData">
          <IconifyIcon icon="ant-design:reload-outlined" />
          刷新
        </Button>
      </div>
    </div>

    <!-- 搜索和过滤 -->
    <div class="search-section">
      <Row :gutter="16">
        <Col :span="6">
          <Input
            v-model:value="searchForm.capabilityInstanceId"
            placeholder="搜索能力实例ID"
            allow-clear
            @change="handleSearch"
          />
        </Col>
        <Col :span="4">
          <Select
            v-model:value="searchForm.status"
            placeholder="选择状态"
            allow-clear
            @change="handleSearch"
          >
            <SelectOption value="pending">等待中</SelectOption>
            <SelectOption value="running">执行中</SelectOption>
            <SelectOption value="completed">已完成</SelectOption>
            <SelectOption value="failed">失败</SelectOption>
            <SelectOption value="cancelled">已取消</SelectOption>
          </Select>
        </Col>
        <Col :span="4">
          <Button type="primary" @click="handleSearch">
            <IconifyIcon icon="ant-design:search-outlined" />
            搜索
          </Button>
        </Col>
      </Row>
    </div>

    <!-- 执行记录列表 -->
    <div class="execution-list">
      <Table
        :columns="columns"
        :data-source="executionList"
        :loading="loading"
        :pagination="pagination"
        row-key="id"
        @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'status'">
            <Tag :color="getStatusColor(record.status)">
              {{ getStatusText(record.status) }}
            </Tag>
          </template>

          <template v-else-if="column.key === 'duration'">
            <span v-if="record.duration">
              {{ formatDuration(record.duration) }}
            </span>
            <span v-else>-</span>
          </template>

          <template v-else-if="column.key === 'actions'">
            <Space>
              <Button type="link" size="small" @click="viewDetail(record)">
                <IconifyIcon icon="ant-design:eye-outlined" />
                查看
              </Button>
              <Button
                v-if="record.status === 'running'"
                type="link"
                size="small"
                danger
                @click="cancelExecution(record)"
              >
                <IconifyIcon icon="ant-design:stop-outlined" />
                取消
              </Button>
              <Button
                v-if="record.status === 'completed'"
                type="link"
                size="small"
                @click="downloadResult(record)"
              >
                <IconifyIcon icon="ant-design:download-outlined" />
                下载结果
              </Button>
            </Space>
          </template>
        </template>
      </Table>
    </div>

    <!-- 执行详情模态框 -->
    <Modal
      v-model:visible="detailModalVisible"
      title="执行详情"
      width="800px"
      :footer="null"
      :destroy-on-close="true"
    >
      <div v-if="currentExecution" class="execution-detail">
        <Descriptions :column="2" bordered>
          <DescriptionsItem label="执行ID">
            {{ currentExecution.id }}
          </DescriptionsItem>
          <DescriptionsItem label="能力实例ID">
            {{ currentExecution.capabilityInstanceId }}
          </DescriptionsItem>
          <DescriptionsItem label="资源ID">
            {{ currentExecution.resourceId }}
          </DescriptionsItem>
          <DescriptionsItem label="状态">
            <Tag :color="getStatusColor(currentExecution.status)">
              {{ getStatusText(currentExecution.status) }}
            </Tag>
          </DescriptionsItem>
          <DescriptionsItem label="开始时间">
            {{ formatTime(currentExecution.startTime) }}
          </DescriptionsItem>
          <DescriptionsItem label="结束时间">
            {{
              currentExecution.endTime
                ? formatTime(currentExecution.endTime)
                : '-'
            }}
          </DescriptionsItem>
          <DescriptionsItem label="执行时长">
            {{
              currentExecution.duration
                ? formatDuration(currentExecution.duration)
                : '-'
            }}
          </DescriptionsItem>
        </Descriptions>

        <!-- 执行参数 -->
        <div class="section">
          <h3>执行参数</h3>
          <pre>{{ JSON.stringify(currentExecution.parameters, null, 2) }}</pre>
        </div>

        <!-- 执行结果 -->
        <div class="section">
          <h3>执行结果</h3>
          <div v-if="currentExecution.result">
            <pre>{{ JSON.stringify(currentExecution.result, null, 2) }}</pre>
          </div>
          <div v-else class="empty-text">暂无结果</div>
        </div>

        <!-- 执行错误 -->
        <div v-if="currentExecution.error" class="section">
          <h3>执行错误</h3>
          <div class="error-info">
            <div class="error-code">
              错误代码: {{ currentExecution.error.code }}
            </div>
            <div class="error-message">
              错误信息: {{ currentExecution.error.message }}
            </div>
            <div v-if="currentExecution.error.details" class="error-details">
              <pre>{{
                JSON.stringify(currentExecution.error.details, null, 2)
              }}</pre>
            </div>
          </div>
        </div>

        <!-- 执行上下文 -->
        <div class="section">
          <h3>执行上下文</h3>
          <Descriptions :column="2" bordered>
            <DescriptionsItem label="用户ID">
              {{ currentExecution.context.userId }}
            </DescriptionsItem>
            <DescriptionsItem label="会话ID">
              {{ currentExecution.context.sessionId }}
            </DescriptionsItem>
            <DescriptionsItem label="请求ID">
              {{ currentExecution.context.requestId }}
            </DescriptionsItem>
          </Descriptions>
        </div>
      </div>
    </Modal>

    <!-- 能力执行模态框 -->
    <CapabilityExecutionModal
      v-model:visible="executeModalVisible"
      @success="onExecuteSuccess"
    />
  </div>
</template>

<style lang="less" scoped>
.capability-execution-manager {
  .manager-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 16px;
    border-bottom: 1px solid #f0f0f0;

    h2 {
      margin: 0;
      color: #262626;
    }

    .header-actions {
      display: flex;
      gap: 8px;
    }
  }

  .search-section {
    margin-bottom: 20px;
    padding: 16px;
    background-color: #fafafa;
    border-radius: 6px;
  }

  .execution-detail {
    .section {
      margin-top: 24px;

      h3 {
        margin-bottom: 12px;
        color: #262626;
        font-size: 16px;
        font-weight: 500;
      }

      pre {
        background-color: #f5f5f5;
        padding: 12px;
        border-radius: 4px;
        font-size: 12px;
        color: #595959;
        overflow-x: auto;
      }

      .error-info {
        background-color: #fff2f0;
        border: 1px solid #ffccc7;
        border-radius: 4px;
        padding: 12px;

        .error-code {
          color: #cf1322;
          font-weight: 500;
          margin-bottom: 8px;
        }

        .error-message {
          color: #cf1322;
          margin-bottom: 8px;
        }

        .error-details {
          pre {
            background-color: #fff;
            border: 1px solid #ffccc7;
          }
        }
      }

      .empty-text {
        color: #8c8c8c;
        text-align: center;
        padding: 20px;
      }
    }
  }
}
</style>
